package atguigu.com.edu.app.dwd.log;

import atguigu.com.edu.util.DateFormatUtil;
import atguigu.com.edu.util.MyKafkaUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;


public class DwdTrafficBaseLogSplit {
    public static void main(String[] args) throws Exception {
        //配置环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(4);
        //设置检查点
    /*    env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //两任务最小时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(600L);
        //是否保留
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.DELETE_ON_CANCELLATION);
        //重启策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
       //设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        //设置地点
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop202:8020/edu/ck");
        System.setProperty("HADOOP_USER_NAME","atguigu");*/

        //3到kafka那log数据
        String topic = "topic_log";
        String groupId = "dwd_traffic_base_log_split_group";
        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getKafkaConsumer(topic, groupId);

        DataStreamSource<String> stringDataStreamSource = env.addSource(kafkaConsumer);

        //stringDataStreamSource.map(JSON::parseObject);
          //stringDataStreamSource.print("....");
     //对数据类型进行转换，不对的放测输出流
        OutputTag<String> outputTag = new OutputTag<String>("Tag") {
        };

        SingleOutputStreamOperator<JSONObject> jsonObj = stringDataStreamSource.process(new ProcessFunction<String, JSONObject>() {
            @Override
            public void processElement(String in, Context context, Collector<JSONObject> out) throws Exception {

                try {
                    JSONObject jsonObject = JSON.parseObject(in);
                    out.collect(jsonObject);
                } catch (Exception e) {
                    context.output(outputTag,in);

                }

            }
        });
            //将脏数据放测输出流里面，放进kafka主题
        DataStream<String> sideOutput = jsonObj.getSideOutput(outputTag);

         sideOutput.addSink(MyKafkaUtil.getKafkaProducer("dirty_data"));

         //对新老用户修复

        KeyedStream<JSONObject, String> jsonKey = jsonObj.keyBy(r -> r.getJSONObject("common").getString("mid"));

        SingleOutputStreamOperator<JSONObject> JMap = jsonKey.map(new RichMapFunction<JSONObject, JSONObject>() {
            private ValueState<String> last;

            @Override
            public void open(Configuration parameters) throws Exception {
                last = getRuntimeContext().
                        getState(new ValueStateDescriptor<String>("last",String.class));
            }
            @Override
            public JSONObject map(JSONObject in) throws Exception {
                String isNew = in.getJSONObject("common").getString("is_new");
                String value = last.value();
                Long ts = in.getLong("ts");
                String curTs = DateFormatUtil.toDate(ts);
                if ("1".equals(isNew)){
                    if (StringUtils.isEmpty(value)){
                last.update(curTs);
                    }else {
                    if (!ts.equals(last)){
                      isNew = "0";
                      in.getJSONObject("common").put("is_new",isNew);
                    }
                    }
                }else {
                    if (StringUtils.isEmpty(value)){
                        String yesterDay = DateFormatUtil.toDate(ts - 24 * 60 * 60 * 1000);
                        last.update(yesterDay);
                    }
            }
                    return in;
            }
        });
       // JMap.print("---");

        OutputTag<String> err = new OutputTag<String>("errTag") {};
        OutputTag<String> dis = new OutputTag<String>("disTag") {};
        OutputTag<String> start = new OutputTag<String>("startTag") {};
        OutputTag<String> action = new OutputTag<String>("actionTag") {};

        SingleOutputStreamOperator<String> page = JMap.process(new ProcessFunction<JSONObject, String>() {

            @Override
            public void processElement(JSONObject in, Context ctx, Collector<String> out) throws Exception {
                JSONObject err1 = in.getJSONObject("err");
                if (err1 != null){
            ctx.output(err,in.toJSONString());
            in.remove("err");
                }

                JSONObject start1 = in.getJSONObject("start");
                if (start1 !=null){
            ctx.output(start,in.toJSONString());
                }else {
                    JSONObject common = in.getJSONObject("common");
                    JSONObject page1 = in.getJSONObject("page");
                    Long ts = in.getLong("ts");
                    JSONArray displays = in.getJSONArray("displays");
                    if (displays !=null && displays.size() >0 ){
                      for (int i = 0; i < displays.size(); i++) {
                          JSONObject newDis = new JSONObject();
                          JSONObject displayJsonObj = displays.getJSONObject(i);
                          newDis.put("common",common);
                          newDis.put("page",page1);
                          newDis.put("display",displayJsonObj);
                          newDis.put("ts",ts);
                          ctx.output(dis,newDis.toJSONString());


                      }

                  }
                    JSONArray actionArr = in.getJSONArray("actions");
                    if (actionArr != null && actionArr.size() > 0){
                        for (int i = 0; i < actionArr.size(); i++) {
                            JSONObject newDis = new JSONObject();
                            JSONObject jsonObject = actionArr.getJSONObject(i);

                            newDis.put("common",common);
                            newDis.put("page",page1);
                            newDis.put("action",jsonObject);


                            ctx.output(action,newDis.toJSONString());

                        }

                    }

                    in.remove("actions");
                    in.remove("displays");
                    out.collect(in.toJSONString());
                }


            }
        });
        DataStream<String> sideOutput1 = page.getSideOutput(err);
        DataStream<String> sideOutput2 = page.getSideOutput(dis);
        DataStream<String> sideOutput3 = page.getSideOutput(action);
        DataStream<String> sideOutput4 = page.getSideOutput(start);


        page.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_page_log"));
        sideOutput1.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_err_log"));
        sideOutput2.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_displays_log"));
        sideOutput3.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_actions_log"));
        sideOutput4.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_start_log"));

        sideOutput1.print("aaaa");
        sideOutput2.print("》》》》");
        sideOutput3.print("----");
        sideOutput4.print(">>>>>");


        env.execute();
    }
}
